package com.wang.hrm.service.impl;

import com.wang.hrm.domain.Employee;
import com.wang.hrm.domain.Meal;
import com.wang.hrm.domain.Tenant;
import com.wang.hrm.dto.TenantEnteringDto;
import com.wang.hrm.mapper.EmployeeMapper;
import com.wang.hrm.mapper.TenantMapper;
import com.wang.hrm.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wang.hrm.util.encrypt.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wang
 * @since 2020-04-23
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void entering(TenantEnteringDto dto) {
        //1.判断基本参数
        Tenant tenant = dto.getTenant();
        Employee employee = dto.getEmployee();
        Long mealId = dto.getMealId();
        if(!StringUtils.hasLength(tenant.getCompanyName())){
            throw new RuntimeException("公司名称不能为空");
        }

        //2.保存机构，员工表需要机构的id
        Tenant saveTenant = new Tenant();
        saveTenant.setAddress(tenant.getAddress());
        saveTenant.setCompanyName(tenant.getCompanyName());
        saveTenant.setCompanyNum(tenant.getCompanyNum());
        saveTenant.setLogo(tenant.getLogo());
        saveTenant.setTenantType(tenant.getTenantType());

        Date now = new Date();
        saveTenant.setRegisterTime(now);
        saveTenant.setState(Tenant.STATE_NORMAL);  //机构可用
        baseMapper.insert(saveTenant);  //直接把页面传入将来的数据进行保存其实很危险。

        //3.保存管理员账号
        Employee saveEmployee = new Employee();
        saveEmployee.setEmail(employee.getEmail());

        //密码要不要加密
        String enPass = MD5.getMD5(employee.getPassword() + "itsource");

        saveEmployee.setPassword(enPass);
        saveEmployee.setTel(employee.getTel());
        saveEmployee.setUsername(employee.getUsername());
        saveEmployee.setState(Employee.STATE_NORMAL);
        saveEmployee.setInputTime(now);
        saveEmployee.setTenantId(saveTenant.getId());
        saveEmployee.setType(Employee.TYPE_ADMIN);
        employeeMapper.insert(saveEmployee);

        //4.保存机构和套餐的中间表
        baseMapper.insertRelationWithMeal(mealId , saveTenant.getId(), Meal.STATE_UN_PAY);
    }
}
